package io.codescience.aianaly.controller;

import io.codescience.aianaly.model.User;
import io.codescience.aianaly.repository.UserRepository;
import io.codescience.aianaly.utils.AuthUtil;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/profile")
public class UserProfileController {

    private final UserRepository userRepository;
    private static final String DEFAULT_AVATAR = "/static/images/img_03.png"; // 默认头像路径

    private static final String[] AVATAR_OPTIONS = {
            "/static/images/img_01.png",
            "/static/images/img_02.png",
            "/static/images/img_03.png",
            "/static/images/img_04.jpg",
            "/static/images/img_05.jpg",
            "/static/images/img_06.jpg",
            "/static/images/img_07.jpg",
    };

    public UserProfileController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }


    // 权限检查中间方法 - 允许所有登录用户访问
    private String checkLoginAndRedirect(HttpSession session) {
        if (!AuthUtil.isLoggedIn(session)) {
            return "redirect:/login";
        }
        return null;
    }

    @GetMapping
    public String profile(HttpSession session, Model model) {
        String redirect = checkLoginAndRedirect(session);
        if (redirect != null) {
            return redirect;
        }

        User sessionUser = AuthUtil.getCurrentUser(session);
        User currentUser = userRepository.findById(sessionUser.getId())
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 设置默认头像URL如果不存在
        if (currentUser.getAvatarUrl() == null ||
                currentUser.getAvatarUrl().isEmpty() ||
                !Files.exists(Paths.get("src/main/resources" + currentUser.getAvatarUrl()))) {
            currentUser.setAvatarUrl(DEFAULT_AVATAR);
            userRepository.save(currentUser); // 保存到数据库
        }

        model.addAttribute("avatarOptions", AVATAR_OPTIONS);
        model.addAttribute("currentUser", currentUser);
        return "profile"; // 使用普通用户的profile页面
    }

    @PostMapping("/select-avatar")
    public String selectAvatar(@RequestParam("avatarUrl") String avatarUrl,
                               HttpSession session,
                               RedirectAttributes redirectAttributes) {
        String redirect = checkLoginAndRedirect(session);
        if (redirect != null) {
            return redirect;
        }

        try {
            User sessionUser = AuthUtil.getCurrentUser(session);
            User currentUser = userRepository.findById(sessionUser.getId())
                    .orElseThrow(() -> new RuntimeException("用户不存在"));

            boolean isValidAvatar = false;
            for (String option : AVATAR_OPTIONS) {
                if (option.equals(avatarUrl)) {
                    isValidAvatar = true;
                    break;
                }
            }

            if (isValidAvatar) {
                currentUser.setAvatarUrl(avatarUrl);
                userRepository.save(currentUser);
                // 更新session中的用户信息
                session.setAttribute("user", currentUser);
                redirectAttributes.addFlashAttribute("success", "头像更新成功");
            } else {
                redirectAttributes.addFlashAttribute("error", "无效的头像选择");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "头像更新失败: " + e.getMessage());
        }

        return "redirect:/profile";
    }
}
